package it.polimi.swim.servlet;

import it.polimi.swim.entity.Skill;
import it.polimi.swim.session.SkillManagerBeanRemote;
import it.polimi.swim.session.SystemUserManagerBeanRemote;

import java.io.IOException;
import java.util.Properties;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CreateSkillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private Context ctx;
	
    public CreateSkillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			
			ctx = new InitialContext();
			Object ref = ctx.lookup("SkillManagerBean/remote");
			SkillManagerBeanRemote skillManager = (SkillManagerBeanRemote) ref;
			
			List<Skill> skill = skillManager.getUncheckedSkill();
			request.setAttribute("skillList", skill);
			System.out.println("Session bean");
		
			request.getRequestDispatcher("/valutateSkill.jsp").forward(request, response);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			
			String skill;
			
			ctx = new InitialContext();
			Object ref = ctx.lookup("SkillManagerBean/remote");
			SkillManagerBeanRemote skillManager = (SkillManagerBeanRemote) ref;
			
			if((skill=request.getParameter("skill"))!=null)	{		
				skillManager.createSkill(skill);
				request.getRequestDispatcher("/homeAdmin.jsp").forward(request, response);
			}else{
				
				skillManager.validateSkill(request.getParameter("skillId"));
				request.getRequestDispatcher("/homeAdmin.jsp").forward(request, response);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
